<?php
/**
 * Created by PhpStorm.
 * User: lhl
 * Date: 2020/10/20
 * Time: 13:02
 * Features: 角色/用户中间表
 */

namespace app\adminapiv3\model;


use think\Db;

class ServerUserGroupMappingModel extends BaseModel
{

    /**
     * 查询单个角色下的用户数
     * @param int    $groupId 角色id
     */
    public function getGroupUserCount($groupId){
        return $this->alias('g')
            ->join('server_user a','g.user_id=a.id','left')
            ->where([
                'g.group_id' => $groupId,
            ])->count();
    }

    /**
     * 查询多个角色下的用户数
     * @param array $groupIds 角色id数组或字符串
    */
    public function getGroupUserListCount(array $groupIds){
        $countData = $this->alias('g')
            ->fieldRaw('g.group_id,COUNT(g.user_id) as num')
            ->join('server_user a','g.user_id=a.id','left')
            ->where([
                ['g.group_id' ,'in',$groupIds]
            ])->group('g.group_id')->select();
        $data = [];
        foreach ($groupIds as $key => $item){
            //每一项默认为0
            $data[$key] = [
                'group_id' => $item,
                'num' => 0
            ];
            //匹配用户数
            foreach ($countData as $k => $v){
                if($v['group_id'] == $item){
                    $data[$key]['num'] = $v['num'];
                    break;
                }
            }
        }
        return $data;
    }

    /**
     * 根据用户id查询其角色、权限、菜单数据
     * @param int $userId 用户id
    */
    public function getRbacByUserId($userId,$isMenuJson = false){
        //根据用户id查询用户信息
        $userInfo = Db::name('server_user')
            ->field('id,real_name,show_name,level')
            ->where('id' ,$userId)->find();

        return $this->getRbacInfo($userInfo,$isMenuJson);
    }

    /**
     * 根据用户信息查询其角色、权限、菜单数据
     * @param array $userInfo 用户数据
     *
     * @return array
     * [
     *      'rbac' => [
     *          'roles' => 角色数据
     *          'auths' => 权限数据
     *          'route' => 权限路由(去重后)
     *          'menu' =>  菜单html字符串
     *      ]
     * ]
     * @param bool $isMenuJson 菜单是否转换为json格式
     */
    public function getRbacInfo($userInfo,$isMenuJson = false){
        //查询该用户的角色信息
        $userInfo['rbac']['roles'] = $this->alias('g')
            ->join('server_user_group r','g.group_id=r.id','left')  //连结角色表
            ->where([
                'g.user_id' => $userInfo['id'], //该用户的角色数据
            ])->field('r.id as group_id,r.role,r.description,r.is_root as is_root_group')->select()->toArray();

        //如果没有生效的角色,则权限数据也为空
        if(!$userInfo['rbac']['roles']){
            $userInfo['rbac']['roles'] = null;
            $userInfo['rbac']['auths'] = null;
            $userInfo['rbac']['route'] = null;
            $userInfo['rbac']['menu'] = null;
            return $userInfo;
        }

        //判断是否为超级管理员组
        $isRootGroup = false;
        foreach ($userInfo['rbac']['roles'] as $item){
            if($item['is_root_group']){
                $isRootGroup = true;
                break;
            }
        }


        //查询权限数据
        $roleIdStr = implode(',',array_column($userInfo['rbac']['roles'],'group_id'));
        //非超级管理员角色,查询该角色拥有的权限
        if(!$isRootGroup){
            $roleIdStr = implode(',',array_column($userInfo['rbac']['roles'],'group_id'));
            $res = \model('ServerGroupAuthMapping')->getAuthByRoleStr($roleIdStr);
        }else{
            $res = \model('ServerGroupAuthMapping')->getAllAuth($roleIdStr);
        }

        $userInfo['rbac']['auths'] = $res['auths'];
        $userInfo['rbac']['route'] = $res['route'];
        $userInfo['rbac']['menu'] = \model('ServerPermission')->getMenu($userInfo['rbac']['auths'],$isMenuJson);
        return $userInfo;
    }


}